<template>
  <div class="box"></div>
  {{ b }}
  <button @click="add">添加</button>
  <canvas id="mycanvas" width="300" height="300"></canvas>
</template>
<script setup>
import { onMounted, ref } from 'vue'
const add = () => {
  console.log(`helloworld`)

  //A 100
  //A 50
  //
}

onMounted(() => {
  const b = ref(0)

  const canvas = document.getElementById('mycanvas')
  const ctx = canvas.getContext('2d')
  ctx.font = '12px Arial'
  ctx.textBaseline = 'top'
  const drawText = (ctx, text, x = 0, y = 0, width = 0, max_lines = 0, lineHeight = 18, ellipsis = '...') => {
    let lines = []
    const addLine = (drawLine) => {
      let line_metrics = ctx.measureText(drawLine)
      let line_height = line_metrics.fontBoundingBoxDescent - line_metrics.fontBoundingBoxAscent
      let line_y = (lineHeight - line_height) / 2
      lines.push({
        drawLine,
        metrics: line_metrics,
        y: line_y
      })
    }
    if (width > 0) {
      let textArr = text.split('')
      let lineText = []
      let i = 0
      while (textArr.length) {
        let charText = textArr.shift()
        if (!charText) {
          break
        } else {
          lineText.push(charText)
          let text
          let isEndLine = lines.length == max_lines - 1

          if (isEndLine) {
            text = ctx.measureText(lineText.join('') + ellipsis)
          } else {
            text = ctx.measureText(lineText.join(''))
          }
          if (text.width > width) {
            //先弹出渲染
            lineText.pop()
            if (lineText.length) {
              let drawLine
              if (isEndLine) {
                drawLine = lineText.join('') + ellipsis
              } else {
                drawLine = lineText.join('')
              }
              addLine(drawLine)
              //渲染结束再加入
              lineText = [charText]
              if (lines.length == max_lines) {
                lineText = []
                break
              }
            }
          }
        }
      }
      if (lineText.length) {
        addLine(lineText.join(''))
      }
      lines.forEach((res, index) => {
        ctx.fillText(res.drawLine, x, y + index * lineHeight + res.y)
      })
    } else {
      ctx.fillText(text, x, y + lineHeight)
    }
  }

  drawText(ctx, '这这这这这这里测试宽度里测试宽度里测试宽度里测试宽度里测试宽度里测测测测测测测试宽度试宽度试宽度试宽度试宽度试宽度试宽度', 0, 0, 300, 2, 40, '...末尾')
})
</script>
<style type="text/css">
.box {
  width: 100px;
  height: 100px;
  border: 1px solid #000;
}
</style>
